package com.github.leecho.spring.cloud.gateway.dubbo.argument;

import com.github.leecho.spring.cloud.gateway.dubbo.argument.rewirte.DubboArgumentRewriter;
import com.github.leecho.spring.cloud.gateway.dubbo.route.DubboRoute;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.core.io.buffer.DataBufferUtils;
import org.springframework.web.server.ServerWebExchange;

import java.util.HashMap;
import java.util.Map;

/**
 * @author LIQIU
 * @date 2021/7/5 9:06
 */
public class DubboArgumentResolver {

	private final DubboArgumentRewriter rewriter;

	private final HttpRequestBodyReader reader;

	public DubboArgumentResolver(DubboArgumentRewriter rewriter,
								 HttpRequestBodyReader reader) {
		this.rewriter = rewriter;
		this.reader = reader;
	}

	@SuppressWarnings({"unchecked"})
	public Map<String, Object> resolve(DubboRoute route, ServerWebExchange exchange, DataBuffer body) {
		Map<String, Object> payload = (Map<String, Object>) reader.read(exchange, body);
		DataBufferUtils.release(body);
		if (payload != null) {
			if (route.getRewrite() != null && route.getRewrite().size() > 0) {
				return rewriter.rewrite(route.getRewrite(), exchange, payload);
			} else {
				return payload;
			}
		}
		return new HashMap<>(0);
	}

}
